// router.js
import {
	RouterMount,
	createRouter,
	runtimeQuit
} from 'uni-simple-router';
import {
	getToken,
} from '@/utils/auth.js';
import store from './store'

const router = createRouter({
	platform: process.env.VUE_APP_PLATFORM,
	routes: [...ROUTES, {
		path: '*',
		redirect: (to) => {
			return {
				name: 'home'
			}
		}
	}],
	routerErrorEach: ({
		type,
		level,
		...args
	}) => {
		// #ifdef APP-PLUS
		if (type === 3) {
			router.$lockStatus = false
			const pages = getCurrentPages()
			const currentPage = pages[pages.length - 1]
			if (level == 1 && args.uniActualData.from === 'backbutton') {
				if (currentPage.$page.meta.isQuit) {
					runtimeQuit()
				}
			}
		}
		// #endif
	},
});

const whiteList = [
	'/pages/index/index',
	'/pages/index/job/tag',
	'/pages/interview/interview',
	'/pages/my/my',
	'/pages/my/login/login',
	'/pages/common/parse',
]
const getRedirectUrl = (path, query) => {
	let query_str = []
	for (let i in query)
		query_str.push(`${i}=${query[i]}`)
	if (query_str.length)
		return `${path}?${query_str.join('&')}`
	else
		return path
}
//全局路由前置守卫
router.beforeEach(async (to, from, next) => {
	let hasToken = getToken()

	if (hasToken) {
		if (to.path === '/pages/my/login/login') {
			next({
				path: '/',
				NAVTYPE: 'pushTab'
			})
		} else {
			if (store.state.name)
				next()
			else
				try {
					await store.dispatch('getUserInfo')
					next()
				} catch (error) {
					await store.dispatch('resetToken')
					console.log(error)
					next({
						path: `/pages/my/login/login`,
						query: {
							redirect: getRedirectUrl(to.path, to.query)
						},
						NAVTYPE: 'push'
					})
				}
		}
	} else {
		if (whiteList.indexOf(to.path) !== -1) {
			next()
		} else {
			next({
				path: `/pages/my/login/login`,
				query: {
					redirect: getRedirectUrl(to.path, to.query)
				},
				NAVTYPE: 'push'
			})
		}
	}
});
// 全局路由后置守卫
router.afterEach((to, from) => {
	console.log('跳转结束')
})

export {
	router,
	RouterMount
}